"""
自定义分页
"""
from collections import OrderedDict
from django.core import paginator as _paginator
from django.core.paginator import Paginator as DjangoPaginator
from rest_framework.pagination import PageNumberPagination, _positive_int
from rest_framework.response import Response


class CustomPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'limit'
    max_page_size = 999
    django_paginator_class = DjangoPaginator

    def get_paginated_response(self, data):
        code = 2000
        msg = 'success'
        res = {
            'has_next': self.page.has_next(),
            'has_prev': self.page.has_previous(),
            'page': int(self.get_page_number(self.request, _paginator)) or 1,
            'total': self.page.paginator.count,
            'limit': int(self.get_page_size(self.request)) or 10,
            'data': data,

        }
        if not data:
            code = 2000
            msg = '暂无数据'
            res['data'] = []

        return Response(OrderedDict([
            ('code', code),
            ('msg', msg),
            ('data', res),
        ]))

    def get_page_number(self, request, paginator):
        if request.method == 'GET':
            page_number = request.query_params.get(self.page_query_param, 1)
        else:
            page_number = request.data.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = paginator.num_pages
        return page_number

    def get_page_size(self, request):
        if self.page_size_query_param:
            try:
                if request.method == 'GET':
                    page_size = request.query_params[self.page_size_query_param]
                else:
                    page_size = request.data[self.page_size_query_param]
                return _positive_int(page_size, strict=True, cutoff=self.max_page_size)
            except (KeyError, ValueError):
                pass

        return self.page_size
